#!usr/bin/python3

#
# If the parameter defaults, run all test samples
# otherwise, only the specified samples will be tested
#

import sys
import os
import time

# default input path
input_bin = 'input'

# test mode corresponding to data sets
mode = {
    'input/instances_01_KP_FSU' : '1',
    'input/large-scale_UU' : '2',
    'input/low-dimensional_UU' : '0',
}

# implemented algorithms
algorithm = ['dp', 'dfs', 'bfs']

# algorithm usage strategy
strategy = {
    'input/instances_01_KP_FSU' : (1, 0, 0),
    'input/large-scale_UU' : (0, 0, 0),
    'input/low-dimensional_UU' : (1, 0, 0),
}

# set time limit
time_limit = '10s'

def time_translate(time):
    if time.isdigit():
        return float(time)
        
    suffix = time[-1]
    base = float(time[0 : len(time) - 1])
    rules = {
        's' : base,
        'm' : base * 60,
        'h' : base * 3600,
        'd' : base * 86400,
    }
    temp =  rules.get(suffix, base)
    return temp

def test(path):
    if os.path.isfile(path):
        exec(path, os.path.split(path)[0])
    else:
        for root, dirs, files in os.walk(path):
            for name in files:
                exec(os.path.join(root, name), root)

def exec(file, path):
    print('[%s]\nstarting...' %file)
    for index, method in enumerate(algorithm):
        # if the algorithm has not been selected
        if strategy[path][index] == 0:
            continue

        # redirect the running results to the log file
        logname = 'output/%s-%s.log' %(os.path.split(file)[1], method)

        print('test {}'.format(method), end = '')
        time_start = time.time()

        # run test script
        os.system('bash test.sh %s %s %s %s %s' %(str(index), mode[path], file, logname, time_limit))

        time_end = time.time()
        print('(%s s)' %(time_end - time_start), end = ': ')

        found = False
        with open(logname, 'r') as logfile:
            log = logfile.readlines()
            for line in log:
                if 'test passed' in line:
                    found = True
                    break

        if found:
            # sample passed
            print('\033[1;32mPASS!\033[0m')
            os.remove(logname)
            continue

        if (float)(time_end - time_start) >= time_translate(time_limit):
            # timeout
            print('\033[1;33mTIMEOUT!\033[0m')
            os.remove(logname)
            continue  

        # the sample failed the test
        print('\033[1;31mFAIL!\033[0m see %s for more information' %logname)

if __name__ == '__main__':
    argc = len(sys.argv)
    if argc == 1:
        test(input_bin)
    for item in sys.argv:
        if item == sys.argv[0]:
            continue
        test(item)